package comment

import (
	"community-service/cmd/api/internal/models/model"
	"community-service/cmd/api/internal/svc"
	"community-service/cmd/api/internal/types"
	e "community-service/pkg/errorx"
	"context"
	"google.golang.org/grpc/codes"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserApprovePostCommentLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserApprovePostCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserApprovePostCommentLogic {
	return &UserApprovePostCommentLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserApprovePostCommentLogic) UserApprovePostComment(req *types.UserPostCommentApproveReq) (resp *types.Empty, err error) {
	// 参数验证
	if req.Id <= 0 {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.ErrorParam)
	}

	if req.UserId <= 0 {
		return nil, e.NewGrpcErr(codes.InvalidArgument, e.ErrorParam)
	}

	// 检查评论是否存在
	var comment model.CsCommunityPostComment
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostComment{}).
		Where("id = ?", req.Id).Find(&comment).Error; err != nil {
		logx.Errorf("查询评论失败: %v", err)
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if comment.ID == 0 {
		return nil, e.NewGrpcErr(codes.NotFound, e.CommentNotFound)
	}

	// 检查是否已经点赞过
	var existingApprove model.CsCommunityPostCommentApprove
	if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostCommentApprove{}).
		Where("comment_id = ? AND create_user = ?", req.Id, req.UserId).
		Find(&existingApprove).Error; err != nil {
		logx.Errorf("查询评论点赞记录失败: %v", err)
		return nil, e.NewGrpcErr(codes.Internal, e.DBError)
	}

	if req.Action {
		// 点赞操作
		if existingApprove.ID > 0 {
			// 已经点赞过，不需要重复操作
			return &types.Empty{}, nil
		}

		// 创建点赞记录
		approve := &model.CsCommunityPostCommentApprove{
			PostID:    comment.PostID,
			CommentID: req.Id,
			CreateUser: req.UserId,
		}

		if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostCommentApprove{}).
			Create(approve).Error; err != nil {
			logx.Errorf("创建评论点赞记录失败: %v", err)
			return nil, e.NewGrpcErr(codes.Internal, e.DBError)
		}
	} else {
		// 取消点赞操作
		if existingApprove.ID == 0 {
			// 没有点赞记录，不需要操作
			return &types.Empty{}, nil
		}

		// 删除点赞记录
		if err = l.svcCtx.DB.WithContext(l.ctx).Model(&model.CsCommunityPostCommentApprove{}).
			Where("id = ?", existingApprove.ID).Delete(&model.CsCommunityPostCommentApprove{}).Error; err != nil {
			logx.Errorf("删除评论点赞记录失败: %v", err)
			return nil, e.NewGrpcErr(codes.Internal, e.DBError)
		}
	}

	return &types.Empty{}, nil
}
